<template>
  <div>
    <form-content
      :rules="formItems2Rules"
      :form-items="formItems"
      :submitApi="detail.id ? update : add"
      :afterSubmit="afterSubmit"
      :formStateInit="detail"
      :beforeSubmit="beforeSubmit"
    >
      <template #pic="{ item, formState }">
        <div class="">
          <Uploader v-model:value="formState.pic" :maxLen="2" />
        </div>
      </template>
      <template #contenttype="{ item, formState }">
        <a-space direction="vertical">
          <a-radio-group
            :options="types"
            v-model:value="formState[item.name].type"
          />
          <a-input
            v-model:value="formState[item.name].content"
            placeholder="请输入新闻链接"
            :style="{ display: formState[item.name].type == 0 ? '' : 'none' }"
          ></a-input>
          <div
            :style="{ display: formState[item.name].type == 1 ? '' : 'none' }"
          >
            <RichText v-model:value="formState[item.name].content" />
          </div>
        </a-space>
      </template>
    </form-content>
  </div>
</template>

<script>
  import { ref, toRefs, reactive, onMounted, defineComponent } from 'vue';
  import { useRouter, useRoute } from 'vue-router';
  import { formItems, formItems2Rules, types } from './config';
  import { add, update, info } from './api';

  export default defineComponent({
    data() {
      return {
        add,
        update,
        info,
        formItems,
        formItems2Rules,
      };
    },
    setup(props, context) {
      const route = useRoute();
      const router = useRouter();
      const state = reactive({
        detail: {},
      });
      const geiDetail = () => {
        info({
          id: parseInt(route.params.id),
        }).then((res) => {
          state.detail = {
            ...res.data,
            contentType: {
              type: res.data.type,
              content: res.data.content,
            },
            pic: [res.data.pic],
          };
        });
      };

      onMounted(() => {
        if (route.params.id) {
          geiDetail();
        } else {
          state.detail = {};
        }
      });
      const afterSubmit = (res) => {
        router.push('/space/news');
      };

      const beforeSubmit = (params) => {
        if (route.params.id) {
          params.id = parseInt(route.params.id);
        }
        params.pic = params.pic[0];
        params.type = params.contentType.type;
        params.content = params.contentType.content;
        delete params.contentType;
        return params;
      };

      return {
        afterSubmit,
        beforeSubmit,
        types,
        ...toRefs(state),
      };
    },
  });
</script>
